<template>
  <div class="channels-view">
      <Spin fix v-if="loading"></Spin>
      <Layout class="layout">
          <Content class="content">
              <single-view ref="single" 
              :trendData="trend_data" 
              :showindex="current_view_index"
              :testIdLines="testid_lines_data"
              :channel2GoodText="channel_name_func"
              :count_in_selection="count_in_selection"
              :channel2danwei="channel2danwei"
              :raw="raw"></single-view>
              <double-view ref="double"
              :trendData="trend_data" 
              :showindex="current_view_index"
              :testIdLines="testid_lines_data"
              :channel2GoodText="channel_name_func"
              :channel2danwei="channel2danwei"
              :count_in_selection="count_in_selection"
              :raw="raw"
              ></double-view>
              <!-- <six-view  :showindex="current_view_index"
              :trendData="trend_data" 
              :testIdLines="testid_lines_data"></six-view> -->
              <triple-view ref="triple"
              :showindex="current_view_index"
              :trendData="trend_data" 
              :testIdLines="testid_lines_data"
              :channel2GoodText="channel_name_func"
              :channel2danwei="channel2danwei"
              :count_in_selection="count_in_selection"
              :raw="raw"></triple-view>
          </Content>
          <Sider class="h-sider-for-channels">
            <Button type="primary" class="h-to-load-data" @click="$_loadData" :disabled="!able_to_load">{{load_hint}}</Button>
              <div class="h-view-number">View Number</div>
              <div>
                  <ButtonGroup class="h-button-group">
                      <Button :type="(current_view_index==0)?'primary':'ghost'" @click="$_changeViewIndex(0)">1</Button> 
                      <Button :type="(current_view_index==1)?'primary':'ghost'" @click="$_changeViewIndex(1)">2</Button>
                      <Button :type="(current_view_index==3)?'primary':'ghost'" @click="$_changeViewIndex(3)">3</Button>
                      <!-- <Button :type="(current_view_index==2)?'primary':'ghost'" @click="$_changeViewIndex(2)">6</Button> -->
                  </ButtonGroup>
                  
                  <div class="h-sensor-channels">Sensor Channels</div>
                  <single-select :showIndex="current_view_index" :raw_string="raw_string"
                  @single-channel="$_setSingleChannel" :channel2GoodText="channel_name_func"
                  :channels="channels"></single-select>
                  <double-select :showIndex="current_view_index" :raw_string="raw_string"
                  @double-channels="$_setDoubleChannels"  :channel2GoodText="channel_name_func"
                  :channels="channels"></double-select>
                  <triple-select :showIndex="current_view_index" :raw_string="raw_string"
                  @triple-channels="$_setTripleChannels"  :channel2GoodText="channel_name_func"
                  :channels="channels"></triple-select>
              </div>
          </Sider>
      </Layout>
  </div>
</template>

<script>
/* eslint-disable */
/**
 * @description 数据提供端按照一定间距采的样,目前是50,可能改到100
 */
import Debug from "debug";
import axios from "axios";
import _ from "lodash";
import SingleView from "./SingleView";
import DoubleView from "./DoubleView";
import TripleView from "./TripleView";
import SingleSelect from "./SingleSelect";
import DoubleSelect from "./DoubleSelect";
import TripleSelect from "./TripleSelect";
import { StringDecoder } from 'string_decoder';

const dbg = Debug("ChannelsView.vue");
dbg.enabled = true;

export default {
  name: "channels-view",
  components: {
    SingleView,
    DoubleView,
    TripleView,
    SingleSelect,
    DoubleSelect,
    TripleSelect
  },
  data() {
    return {
      current_view_index: 0,
      raw: {
        dates: [],
        types: [],
        test_ids: []
      },
      count_in_selection: 0,
      trend_data: {
        //type 2 data
      },
      testid_lines_data: {
        //id 2 data
      },
      channels: [],
      loading: false,
      channel_name_func: function(channel) {
        if (channel.startsWith("T") || channel.startsWith("t")) {
          return channel;
        }
        channel = channel.toUpperCase();
        if (channel.includes("30")) {
          return channel.replace("30", "s");
        }
        if (channel.includes("45")) {
          return channel.replace("45", "м");
        }
        if (channel.includes("50")) {
          return channel.replace("50", "в");
        }
        if (channel.includes("SPEED")) {
          return channel.replace("SPEED", "Se");
        }

        return channel;
      }
    };
  },
  async created() {
    this.loading = true;
    let axresp = await axios
      .get("/starter/channel_list/")
      .catch(e => (this.loading = false));
    this.channels = axresp.data["channels"];
    this.loading = false;
  },
  computed: {
    starterId() {
      return this.$store.state.starterId;
    },
    load_hint() {
      if (this.raw.dates.length && this.raw.types.length) {
        return "LOAD DATA";
      } else {
        return "BRUSH FIRST";
      }
    },
    able_to_load() {
      return this.raw.dates.length && this.raw.types.length;
    },
    raw_string() {
      return JSON.stringify(this.raw);
    },
    channel2danwei(){
      return function (channel_raw){
        let channel = String(channel_raw).toLowerCase();
        if(channel=="speed"){
          return "RPM"
        }
        if(channel.startsWith("i")){
          return "A"
        }
        if(channel.startsWith("u")){
          return "V"
        }
        return "";
      }
    }
  },
  methods: {
    /**@param {Number} index
     * @api private
     *change the view of channel's graph
     */
    $_changeViewIndex(index) {
      index = parseInt(index);
      index <= 3 && index >= 0
        ? (this.current_view_index = index)
        : this.$Notice.error({
            title: `Illegal Index (at ChannelsView.vue)`,
            duration: 1000
          });
    },
    /**
     * @access public
     */
    setDatesAndTypes(dates, types) {
      this.raw.dates = dates;
      this.raw.types = types;
      dbg("%j", { dates });
      dbg("%j", { types });
    },
    async $_loadData() {
      return;
      this.loading = true;
      try {
        let types_by_dates = (await axios.get(
          "starter/overview/selection/types_by_dates/",
          {
            params: {
              starterId: this.starterId,
              dates: this.raw.dates
            }
          }
        )).data;
        if (_.isArray(types_by_dates)) {
          types_by_dates = types_by_dates.map(e => String(e));
          let good_types = this.raw.types.filter(type =>
            types_by_dates.includes(type)
          );
          let promises = good_types.map(type =>
            axios
              .get("starter/overview/selection/trend/", {
                params: {
                  starterId: this.starterId,
                  types: [type],
                  dates: this.raw.dates
                }
              })
              .then(axresp => {
                if (_.isEmpty(axresp.data)) {
                  this.$set(this.trend_data, type, null);
                } else {
                  this.$set(this.trend_data, type, axresp.data);
                }
              })
          );
          let axresps = await Promise.all(promises);
          // debugger
          this.loading = false;
          //不在raw.types里的都删掉数据
          for (let i in this.trend_data) {
            if (!good_types.includes(i)) {
              this.$set(this.trend_data, i, null);
            }
          }
        }
      } catch (e) {
        this.loading = false;
        this.$Notice.error({
          title: "Request Failed"
        });
      }
    },
    async $_loadDataByChannel(channel) {
      this.loading = true;
      try {
        let types_by_dates = (await axios.get(
          "starter/overview/selection/types_by_dates/",
          {
            params: {
              starterId: this.starterId,
              dates: this.raw.dates
            }
          }
        )).data;
        if (_.isArray(types_by_dates)) {
          types_by_dates = types_by_dates.map(e => String(e));
          let good_types = this.raw.types.filter(type =>
            types_by_dates.includes(type)
          );
          let get_count_promise = axios
            .get(`starter/overview/selection/counts/`, {
              params: {
                starterId: this.starterId,
                types: good_types,
                dates: this.raw.dates
              }
            })
            .then(axresp => {
              this.count_in_selection = axresp.data["count"];
            });
          await get_count_promise;
          let promises = good_types.map(type =>
            axios
              .get(`starter/overview/selection/trend_by_channel/`, {
                params: {
                  starterId: this.starterId,
                  types: [type],
                  dates: this.raw.dates,
                  channel: channel
                }
              })
              .then(axresp => {
                if (_.isEmpty(axresp.data)) {
                  this.$set(this.trend_data, type, null);
                } else {
                  if (!this.trend_data[type]) {
                    this.$set(this.trend_data, type, axresp.data);
                  } else {
                    this.$set(
                      this.trend_data[type],
                      channel,
                      axresp.data[channel]
                    );
                  }
                }
              })
          );
          let axresps = await Promise.all([...promises, get_count_promise]);
          this.loading = false;
          for (let i in this.trend_data) {
            if (!good_types.includes(i)) {
              this.$set(this.trend_data, i, {});
            }
          }
        }
      } catch (e) {
        this.loading = false;
        this.$Notice.error({
          title: "Request Failed"
        });
      }
    },
    /**@param {Number[]} testids */
    setTestids(testids) {
      this.raw.test_ids = testids;
      // dbg({testids});
      this.$emit("test-id-data-loading", true);
      let promises = testids.map(
        testid =>
          new Promise((resolve, reject) => {
            axios
              .get("/starter/detail/", {
                params: {
                  starterId: this.starterId,
                  testId: testid
                }
              })
              .then(axresp => {
                // dbg(testid);
                // this.$set(this.testid_lines_data, testid, axresp.data);
                resolve([testid, axresp.data]);
              })
              .catch(e => {
                this.$delete(this.testid_lines_data, testid);
                reject(testid);
              });
          })
      );
      Promise.all(promises).then(([...args]) => {
        for (let arg of args) {
          this.$set(this.testid_lines_data, arg[0], arg[1]);
        }
        for (let testid in this.testid_lines_data) {
          // debugger
          if (!testids.includes(Number(testid))) {
            this.$delete(this.testid_lines_data, testid);
          }
        }
        this.$emit("test-id-data-loading", false);
      });
    },
    async $_setSingleChannel(channel) {
      if (this.raw.dates.length && this.raw.types.length) {
        await this.$_loadDataByChannel(channel);
      }
      this.$refs["single"].setChannel(channel);
    },
    async $_setDoubleChannels(channels) {
      if (this.raw.dates.length && this.raw.types.length) {
        for (let channel of channels) {
          await this.$_loadDataByChannel(channel);
        }
      }
      this.$refs["double"].setChannels(channels);
    },
    async $_setTripleChannels(channels) {
      if (this.raw.dates.length && this.raw.types.length) {
        for (let channel of channels) {
          await this.$_loadDataByChannel(channel);
        }
      }
      this.$refs["triple"].setChannels(channels);
    }
  },
  watch: {
    starterId: function(val) {
      this.raw.dates = [];
      this.raw.types = [];
      this.raw.test_ids = [];
      this.trend_data = {};
      this.testid_lines_data = {};
    },
    raw_string: function() {
      this.trend_data = {};
      this.testid_lines_data = {};
    }
  }
};
</script>

<style lang="scss">
.channels-view {
  height: 708px;
  position: relative;
  .layout {
    height: 100%;
    .content {
      height: 100%;
      overflow-y: auto;
    }
    .h-sider-for-channels {
      background-color: #fff;
      padding-left: 10px;
      padding-top: 10px;
      $gray: #b5b5b5;
      $hwidth: 98px;

      div.h-view-number {
        margin-bottom: 5px;
        // padding-right:30px;
        width: $hwidth;
        margin-bottom: 8px;
        font-size: 12px;
        display: inline-block;
        border-bottom: solid 1px $gray;
      }
      .h-button-group {
        &.ivu-btn-group {
          .ivu-btn {
            padding: 0px 6px;
            &:not(:first-child) {
              margin-left: 5px;
            }
          }
          .ivu-btn-primary {
            background-color: $gray;
            border-color: $gray;
            &:focus {
              box-shadow: 0 0 0 0px $gray;
            }
          }
          .ivu-btn-ghost {
            color: $gray;
          }
          .ivu-btn-ghost:focus {
            box-shadow: 0 0 0 0px $gray;
          }
          .ivu-btn-ghost:hover {
            color: $gray;
            border-color: $gray;
          }
          .ivu-btn-primary ~ .ivu-btn {
            border-color: $gray;
          }
        }
      }
      .h-to-load-data {
        display: block;
        margin-top: 5px;
        margin-bottom: 5px;
        padding-top: 2px;
        padding-bottom: 2px;
      }
      .h-sensor-channels {
        // padding-bottom: 5px;
        // display: inline-block;
        border-bottom: solid 1px $gray;
        // text-decoration: underline;
        font-size: 12px;
        padding-top: 10px;
        width: $hwidth;
        // padding-right: 10px;
        margin-left: 0px;
      }
    }
  }
}
</style>
